import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Tabs, Button, Card, Row, Col,Tooltip, Icon } from 'antd';
import { bindActionCreators } from 'redux';
import moment from 'moment';
import { connect } from 'react-redux';
import styles from './OrderDetail.less';
import { CommonTable } from 'components';
import { orderDetailAction } from './index';
import AddUrgeModal from './AddUrgeModal/AddUrgeModal';
import UrgeRecordModal from './UrgeRecordModal/UrgeRecordModal';
import { axios } from 'utils';
const TabPane = Tabs.TabPane;


const backTypeObj = {
    "1": "逾期全款",
    "2": "逾期展期"
};
//还款记录
const backRecordColumns = [
    {
        title: '还款时间',
        dataIndex: 'payTime',
        key: 'payTime',
        render(text) {
            return moment(Number(text) * 1000).format('YYYY-MM-DD HH:mm:ss');
        }
    },
    { title: '支付方式', dataIndex: 'payName', key: 'payName' },
    {
        title: '还款类型',
        dataIndex: 'state',
        key: 'state',
        render(text) {
            return backTypeObj[text] || '';
        }
    },
    { title: '还款金额', dataIndex: 'totalMoney', key: 'totalMoney' },
    { title: '交易流水号', dataIndex: 'payTradeNo', key: 'payTradeNo' },
    { title: '催收人', dataIndex: 'collectorName', key: 'collectorName' }
];
//减免记录
const breaksColumns = [
    {
        title: '减免时间',
        dataIndex: 'reduceTime',
        key: 'reduceTime',
        // render(text) {
        //     return moment(Number(text) * 1000).format('YYYY-MM-DD HH:mm:ss');
        // }
    },
    { title: '减免金额(元)', dataIndex: 'reduceAmount', key: 'reduceAmount' },
    {
        title: '减免类型',
        dataIndex: 'reduceType',
        key: 'reduceType',
        render(text) {
            // return text === 1 ? '滞纳金额' : '';
            return '滞纳金额';
        }
    },
    { title: '催收人', dataIndex: 'reduceOperation', key: 'reduceOperation' }
];
//催收记录
const urgeRecordColumns = [
    {
        title: '添加时间',
        dataIndex: 'createTime',
        key: 'createTime',
        render(text) {
            return moment(Number(text)).format('YYYY-MM-DD HH:mm:ss');
        }
    },
    { title: '催收备注', dataIndex: 'remark', key: 'remark' },
    { title: '催收人', dataIndex: 'collectorname', key: 'collectorname' }
];
//展期记录
const standOverRecordColumns = [
    {
        title: '展期时间',
        dataIndex: 'addTime',
        key: 'addTime',
        render(text) {
            return moment(Number(text) * 1000).format('YYYY-MM-DD HH:mm:ss');
        }
    },
    {
        title: '是否逾期',
        dataIndex: 'expireDays',
        key: 'expireDays',
        render(text) {
            return Number(text) === 0 ? '未逾期' : `逾期${Number(text)}天`;
        }
    },
    { title: '展期费用(元)', dataIndex: 'totalMoney', key: 'totalMoney' },
    { title: '逾期滞纳金(元)', dataIndex: 'overMoney', key: 'overMoney' }
];
//逾期记录
// const overdueRecordColumns = [
//     { title: '订单号', dataIndex: 'orderNo', key: 'orderNo' },
//     {
//         title: '逾期时间',
//         dataIndex: 'expireTime',
//         key: 'collectorName',
//         render(text) {
//             return moment(Number(text) * 1000).format('YYYY-MM-DD HH:mm:ss');
//         }
//     },
//     { title: '催收人', dataIndex: 'collectorName', key: 'collectorName' },
//     {
//         title: '操作',
//         dataIndex: 'id',
//         key: 'id',
//         render(text) {
//             return (
//                 <Tooltip title={'查看催收记录'}>
//                     <div onClick={}>
//                         <Icon type={'edit'}/>
//                     </div>
//                 </Tooltip>
//
//             );
//         }
//     }
// ];

//通话记录
const phoneRecordColumns = [
    { title: '姓名', dataIndex: 'name', key: 'name' },
    { title: '号码', dataIndex: 'phoneNo', key: 'phoneNo' },
    { title: '号码标签', dataIndex: 'phoneTag', key: 'phoneTag' },
    { title: '号码归属地', dataIndex: 'area', key: 'area' },
    { title: '近6月主叫通话次数', dataIndex: 'callCountActive6month', key: 'callCountActive6month' },
    { title: '近6月被叫通话次数', dataIndex: 'callCountPassive6month', key: 'callCountPassive6month' },
    { title: '近3月通话次数', dataIndex: 'callCount3month', key: 'callCount3month' },
    { title: '近3月通话时长(分)', dataIndex: 'callTime3month', key: 'callTime3month' },
    { title: '近6月通话次数', dataIndex: 'callCount6month', key: 'callCount6month' },
    { title: '近6月通话时长(分)', dataIndex: 'callTime6month', key: 'callTime6month' },
];
//短信记录
const msgRecordColumns = [
    { title: '起始时间', dataIndex: 'startTime', key: 'startTime' },
    { title: '发送方式', dataIndex: 'sendType', key: 'sendType' },
    { title: '对方号码', dataIndex: 'number', key: 'number' },
    { title: '短信地区', dataIndex: 'msgAddress', key: 'msgAddress' }
];

class OrderDetail extends Component{
    constructor(props) {
        super(props);
        const { location: { pathname } } = this.props;
        //判断是否显示添加催收记录按钮
        const isShowBtn = pathname.indexOf('overdueList') === -1;

        this.state = {
            remark: '',
            isShowBtn,
            reduceMoney: '',
            reduceTime: '',
            reduceList: []
        };
        const _this = this;
        this.overdueRecordColumns = [
            { title: '订单号', dataIndex: 'orderNo', key: 'orderNo' },
            {
                title: '逾期时间',
                dataIndex: 'expireTime',
                key: 'expireTime',
                render(text) {
                    return moment(Number(text) * 1000).format('YYYY-MM-DD HH:mm:ss');
                }
            },
            { title: '催收人', dataIndex: 'collectorName', key: 'collectorName' },
            {
                title: '操作',
                dataIndex: 'id',
                key: 'id',
                render(text) {
                    return (
                        <Tooltip title={'查看催收记录'}>
                            <div style={{ textAlign: 'center', cursor: 'pointer' }}  onClick={() => _this.lookRecord(text)}>
                                <Icon type={'edit'}/>
                            </div>
                        </Tooltip>

                    );
                }
            }
        ];
    }

    //查看催收记录
    lookRecord = (text) => {
        const { lookUrgeRecord } = this.props;
        lookUrgeRecord({ overdueId: text });
    }

    urgeHandleCancel = () => {
        const { changeRecordVisible } = this.props;
        changeRecordVisible(false);

    }

    renderBtn = () => {
        const { isShowBtn } = this.state;
        const ele = isShowBtn ? <Button type={'primary'} onClick={this.handleBtnClick}>添加催收记录</Button> : null;
        return (
            <div className={styles.btnWrapper}>
                {ele}
                <Button onClick={this.backList}>返回</Button>
            </div>
        );
    }
    //添加催收记录
    handleBtnClick = () => {
        const { changeVisible } = this.props;
        changeVisible(true);
    }
    //返回列表页
    backList = () => {
        const { history: { push }, location: { pathname } } = this.props;
        const pathArr = pathname.split('/');
        const realPath = '/' + pathArr[1];
        push(realPath);
    }
    //渲染订单信息
    renderOrderCard = () => {
        const { orderData: { orderInfo = {} } } = this.props;
        // console.log(orderInfo);
        const info = orderInfo['icloud'] || {};
        const isOlduserStyle = orderInfo['isOlduser'] === '是' ? { color: 'red' } : {};
        const standOverNumberStyle = Number(orderInfo.standOverNumber) > 0 ? { color: 'red' } : {};
        const { reduceMoney, reduceTime, reduceList } = this.state;
        return (
            <div>
                <Card type={'inner'} title={'业务信息'}>
                    <Row gutter={24}>
                        <Col className={styles.col} lg={12} xl={8}><span className={styles.title}>订单号：</span><span>{orderInfo.orderNo}</span></Col>
                        <Col className={styles.col} lg={12} xl={8}><span className={styles.title}>姓名：</span><span>{orderInfo.name}</span></Col>
                        <Col style={isOlduserStyle} className={styles.col} lg={12} xl={8}><span className={styles.title}>是否是老用户：</span><span>{orderInfo['isOlduser']}</span></Col>
                        <Col className={styles.col} lg={12} xl={8}><span className={styles.title}>手机号：</span><span>{orderInfo.phoneNo}</span></Col>
                        {/*<Col className={styles.col} lg={12} xl={8}><span className={styles.title}>手机型号：</span><span>{orderInfo.deviceModel}</span></Col>*/}
                        {/*<Col className={styles.col} lg={12} xl={8}><span className={styles.title}>手机内存：</span><span>{orderInfo.deviceMemory}</span></Col>*/}
                        <Col className={styles.col} lg={12} xl={8}><span className={styles.title}>借款金额(元)：</span><span>{orderInfo.accountMoney}</span></Col>
                        <Col className={styles.col} lg={12} xl={8}><span className={styles.title}>申请时间：</span><span>{orderInfo.applyTime}</span></Col>
                        <Col className={styles.col} lg={12} xl={8}><span className={styles.title}>放款时间：</span><span>{orderInfo.loanTime}</span></Col>
                        <Col className={styles.col} lg={12} xl={8}><span className={styles.title}>申请金额(元)：</span><span>{orderInfo.accountMoney}</span></Col>
                        {/*<Col style={standOverNumberStyle} className={styles.col} lg={12} xl={8}><span className={styles.title}>展期次数：</span><span>{orderInfo.standOverNumber}</span></Col>*/}
                        <Col className={styles.col} lg={12} xl={8}><span className={styles.title}>逾期天数：</span><span>{orderInfo['overdueTime']}</span></Col>
                        <Col className={styles.col} lg={12} xl={8}><span className={styles.title}>应还金额(元)：</span><span>{orderInfo['backMoney']}</span></Col>
                        <Col className={styles.col} lg={12} xl={8}><span className={styles.title}>滞纳金(元)：</span><span>{orderInfo['lateFees']}</span></Col>
                        <Col className={styles.col} lg={12} xl={8}><span className={styles.title}>已还金额(元)：</span><span>{orderInfo['hasBackMoney']}</span></Col>
                        <Col className={styles.col} lg={12} xl={8}><span className={styles.title}>剩余应还(元)：</span><span>{orderInfo['surplusBackMoney']}</span></Col>
                        <Col className={styles.col} lg={12} xl={8}><span className={styles.title}>减免金额(元)：</span><span>{reduceMoney}</span></Col>
                        <Col className={styles.col} lg={12} xl={8}><span className={styles.title}>减免时间：</span><span>{reduceTime}</span></Col>
                        {/*<Col className={styles.col} lg={12} xl={8}><span className={styles.title}>展期费用(元)：</span><span>{orderInfo['standOverMoney']}</span></Col>*/}
                    </Row>
                </Card>
                {/*<Card type={'inner'} title={'iCloud账号信息'} className={styles.card}>*/}
                    {/*<Row gutter={16}>*/}
                        {/*<Col className={styles.col} lg={12} xl={8}><span className={styles.title}>账号：</span><span>{info['icloudNo'] || ''}</span></Col>*/}
                        {/*<Col className={styles.col} lg={12} xl={8}><span className={styles.title}>密码：</span><span>{info['icloudPwd'] || ''}</span></Col>*/}
                        {/*<Col className={styles.col} lg={12} xl={8}><span className={styles.title}>新密码：</span><span>{info['icloudPwdNew'] || ''}</span></Col>*/}
                        {/*/!*<Col className={styles.col} span={12}><span className={styles.title}>问题1：</span><span>{info['icloudSecurityQuestion1'] || ''}</span></Col>*!/*/}
                        {/*/!*<Col className={styles.col} span={12}><span className={styles.title}>答案1：</span><span>{info['icloudSecurityAnswer1'] || ''}</span></Col>*!/*/}
                        {/*/!*<Col className={styles.col} span={12}><span className={styles.title}>问题2：</span><span>{info['icloudSecurityQuestion2'] || ''}</span></Col>*!/*/}
                        {/*/!*<Col className={styles.col} span={12}><span className={styles.title}>答案2：</span><span>{info['icloudSecurityAnswer2'] || ''}</span></Col>*!/*/}
                        {/*/!*<Col className={styles.col} span={12}><span className={styles.title}>问题3：</span><span>{info['icloudSecurityQuestion3'] || ''}</span></Col>*!/*/}
                        {/*/!*<Col className={styles.col} span={12}><span className={styles.title}>答案3：</span><span>{info['icloudSecurityAnswer3'] || ''}</span></Col>*!/*/}
                    {/*</Row>*/}
                {/*</Card>*/}
                <CommonTable columns={backRecordColumns} dataSource={orderInfo['backRecord'] || []} title={() => <div>还款记录</div>}/>
                <CommonTable columns={breaksColumns} dataSource={reduceList} title={() => <div>减免记录</div>}/>
                <CommonTable columns={urgeRecordColumns} dataSource={orderInfo['urgeRecord'] || []} title={() => <div>催收记录</div>}/>
                {/*<CommonTable columns={standOverRecordColumns} dataSource={orderInfo['standOverRecord'] || []} title={() => <div>展期记录</div>}/>*/}
                <CommonTable columns={this.overdueRecordColumns} dataSource={orderInfo['overdueRecord'] || []} title={() => <div>逾期记录</div>}/>

            </div>
        );


    }
    //渲染客户信息
    renderUserInfo = () => {
        const { orderData: { userInfo = {} } } = this.props;
        return (
            <div>
                <Card type={'inner'} title={'个人信息'}>
                    <Row gutter={16}>
                        <Col className={styles.col} lg={12} xl={8}><span className={styles.title}>姓名：</span><span>{userInfo.name || ''}</span></Col>
                        <Col className={styles.col} lg={12} xl={8}><span className={styles.title}>手机号：</span><span>{userInfo.phoneNo || ''}</span></Col>
                        <Col className={styles.col} lg={12} xl={8}><span className={styles.title}>身份证号：</span><span>{userInfo.idCard || ''}</span></Col>
                        <Col className={styles.col} lg={12} xl={8}><span className={styles.title}>家庭住址：</span><span>{userInfo.address || ''}</span></Col>
                        <Col className={styles.col} lg={12} xl={8}><span className={styles.title}>风险等级：</span><span>{userInfo.tdreportDes || ''}</span></Col>
                        <Col className={styles.col} lg={12} xl={8}><span className={styles.title}>同盾分数：</span><span>{userInfo.tdreportPoint}</span></Col>
                        <Col className={styles.col} lg={12} xl={8}><span className={styles.title}>指迷分数：</span><span>{userInfo.zmScore}</span></Col>
                    </Row>
                </Card>
                <div className={styles.card}>
                    <Card type={'inner'} title={'客户资料'}>
                        <Row gutter={96}>
                            <Col className={`${styles.col}`} lg={12} xl={8}>
                                {
                                    userInfo['idCardFrontPhoto'] && <img className={styles.imgCol} width={'100%'} src={userInfo['idCardFrontPhoto']}/>
                                }
                            </Col>
                            <Col className={`${styles.col}`} lg={12} xl={8}>
                                {
                                    userInfo['idCardBackPhoto'] && <img className={styles.imgCol} width={'100%'} src={userInfo['idCardBackPhoto']}/>
                                }

                            </Col>
                            <Col className={`${styles.col}`} lg={12} xl={8}>
                                {
                                    userInfo['idCardPhoto'] && <img className={styles.imgCol} width={'100%'} src={userInfo['idCardPhoto']}/>
                                }
                            </Col>
                        </Row>

                    </Card>
                </div>


            </div>
        );
    }

    //渲染通讯录
    renderAddressBook = () => {
        const { orderData: { addressBook = [] } } = this.props;
        const columns = [
            { title: '姓名', dataIndex: 'contactsName', key: 'contactsName' },
            { title: '手机号', dataIndex: 'contactsPhone', key: 'contactsPhone' }
        ];
        return (
            <CommonTable columns={columns} dataSource={addressBook} title={() => <div>通讯录信息</div>}/>
        );
    }
    //渲染运营商信息
    renderOperatorMsg = () => {
        const { orderData: { operator = {} } } = this.props;
        return (
            <div>
                <CommonTable columns={phoneRecordColumns} dataSource={operator['photoRecord'] || []} title={() => <div>通话记录</div>}/>
                {/*<CommonTable columns={msgRecordColumns} dataSource={operator['msgRecord'] || []} title={() => <div>短信记录</div>}/>*/}
            </div>
        );
    }
    //关闭添加催收记录弹窗
    urgeModalCancel = () => {
        const { changeVisible } = this.props;
        changeVisible(false);
        this.setState({ remark: '' });
    }
    //添加催收记录
    urgeHandleOk = (obj) => {
        const { match, addUrgeRecord, getAllUrgeRecord } = this.props;
        const params = match['params']['id'] || '';
        addUrgeRecord({ ...obj, overdueId: params }, () => {
            getAllUrgeRecord({ overdueId: params });
        });

    }
    // 减免记录
    handleAxios = (data) => {
        axios({
            url: '/hs/admin/orderOverdue/detail',
            method: 'post',
            data
        }).then((res) => {
            // console.log(res)
            if(res.data) {
                const data = res.data
                this.setState({
                    reduceList: data.reduceList || [],
                    reduceMoney: `${data.reduceMoney}` || '',
                    reduceTime: data.reduceTime || ''
                })
                // console.log(this.state)
            }
        })
    }
    componentDidMount() {
        const { match, location: { state }, getOrderData, getAllUrgeRecord } = this.props;
        const userId = state ? state['userId'] : '';
        const params = match['params']['id'] || '';
        getOrderData({ overdueId: params }, { userId });
        this.handleAxios({overdueId:params})
        getAllUrgeRecord({ overdueId: params });
    }
    componentWillUnmount() {
        const { setOrderData } = this.props;
        setOrderData({});
    }

    render() {
        const ele = this.renderBtn();
        const { visible, recordVisible, recordData } = this.props;
        const { remark } = this.state;
        return (
            <div>
                <Tabs animated={false} tabBarExtraContent={ele}>
                    <TabPane tab="订单信息" key="1">
                        {this.renderOrderCard()}
                    </TabPane>
                    <TabPane tab="客户信息" key="2">
                        {this.renderUserInfo()}
                    </TabPane>
                    <TabPane tab="通讯录" key="3">
                        {this.renderAddressBook()}
                    </TabPane>
                    <TabPane tab="运营商" key="4">
                        {this.renderOperatorMsg()}
                    </TabPane>
                </Tabs>
                <AddUrgeModal visible={visible} handleCancel={this.urgeModalCancel} handleOk={this.urgeHandleOk} remark={remark}/>
                <UrgeRecordModal visible={recordVisible} handleCancel={this.urgeHandleCancel} tableData={recordData}/>
            </div>
        );
    }
}

OrderDetail.propTypes = {
    orderData: PropTypes.object,
};
OrderDetail.defaultProps = {
    orderData: {
        orderInfo: {
            orderNo: 1,
            name: 'zs',
            phoneNo: '12345678998',
            loanMoney: '30',
            applyTime: '2018-5-7',
            iCloudAccount: '12345',
            iCloudPassword: '123',
            loanTime: '2018-6-07',
            accountMoney: '30',
            standOverNumber: '2',
            overdueTime: '2018-5-7',
            backMoney: '30',
            lateFees: '10',
            hasBackMoney: '20',
            surplusBackMoney: '10',
            standOverMoney: '10',
            backRecord: [],
            urgeRecord: [],
            standOverRecord: [],
            overdueRecord: [],
            deviceModel: '',
            isOlduser: '1',
            deviceMemory: ''
        },
        userInfo: {
            name: 'zs',
            phoneNo: '1234567892',
            idCard: '123456788945563235',
            address: '浙江省杭州市xxx',
            idCardFrontPhoto: '',
            idCardBackPhoto: '',
            idCardPhoto: ''
        },
        addressBook: [],
        operator: {
            photoRecord: [],
            // msgRecord: []
        }
    }
};
const mapStateToProps = (state) => {
    const { afterLoanManageState: { orderDetailState } } = state;
    return {
        orderData: orderDetailState['orderData'],
        visible: orderDetailState['visible'],
        recordVisible: orderDetailState['recordVisible'],
        recordData: orderDetailState['recordData']
    };
};
const mapDispatchToProps = (dispatch) => {
    return bindActionCreators({
        changeVisible: orderDetailAction.ordChangeModalVisible,
        getOrderData: orderDetailAction.ordGetOrderDetail,
        setOrderData: orderDetailAction.ordSetOrderDetail,
        changeRecordVisible: orderDetailAction.ordChangeRrecordModal,
        lookUrgeRecord: orderDetailAction.ordLookUrgeRecord,
        addUrgeRecord: orderDetailAction.ordAddUrgeRecord,
        getAllUrgeRecord: orderDetailAction.ordGetUrgeRecord
    }, dispatch);
};


export default connect(mapStateToProps, mapDispatchToProps)(OrderDetail);